Java零基础-空指针异常

1
2
3
4
5
6
7
8
Student stu = new Student();
System.out.println(stu.name);

stu = null;
// 以下程序可以 编译通过,因为符合语法
// 运行出现 空指针 异常,java.lang.NullPointerException
// 因为引用的地址变成了空,就没有引用了
System.out.println(stu.name);

注意另一种情况:

带有 static 的方法,其实既可以采用类名的方式访问,也可以采用引用的方式访问。但是即使采用引用的方式去访问,实际上执行的时候和引用指向的对象无关。

在 eclips 中开发的时候,使用引用的方式访问带有 static 的方法,程序会发生警告。

所以带有 static 的方法还是建议使用“类名.”的方式访问

1
2
3
4
5
6
7
8
9
10
public class Text {
public static void main(String[] args) {
Test t = new Text();
t.doSome();

t = null;

t.doSome(); // 不会出现引用异常,因为与引用指向的对象无关
}
}

System.out.pringln()内有乾坤

1
2
3
4
5
6
7
Object[] objs = new Object[3];

for(int i = 0;i < objs.length;i++) {
Object o = objs[i];
// o.toString(); // 空指针异常,因为引用类型的数组默认值是 null
System.out.pringln(o); // null null null
}

为什么上面代码输出不会报空指针异常呢?去println的源码看看吗

1
2
3
4
5
6
7
8
9
10
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString(); // 看这里!已经做了兼容处理
}